import React, { useEffect, useState } from "react";
import { Table, Tag, message, Button } from "antd";
import service from "@/http/request";
import dayjs from "dayjs";
import { CopyOutlined } from "@ant-design/icons";
import { code } from "@uiw/react-md-editor";
import { useSelector } from "react-redux";

const Invitation = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  const role = useSelector((state)=>state.user.role)
  console.log(role)
  // 获取邀请码数据
  const fetchInvites = async () => {
    setLoading(true);
    try {
      const res = await service.get("/invites/all");
      if (res) {
        setData(res || []);
      } else {
        message.error(res?.message || "获取邀请码失败");
      }
    } catch (error) {
      message.error("网络错误，无法获取邀请码");
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchInvites();
  }, []);

  const copyTextFallback = (text) => {
    const textarea = document.createElement("textarea");
    textarea.value = text;

    // 避免页面滚动
    textarea.style.position = "fixed";
    textarea.style.opacity = "0";
    document.body.appendChild(textarea);
    textarea.focus();
    textarea.select();

    try {
      const success = document.execCommand("copy");
      console.log("Fallback copy:", success ? "成功" : "失败");
    } catch (err) {
      console.error("Fallback error:", err);
    }

    document.body.removeChild(textarea);
  };

  // 复制邀请码
  const handleCopy = (code) => {
    // navigator.clipboard.writeText(code);
    copyTextFallback(code);
    document.execCommand("copy");

    message.success("邀请码已复制");
  };

  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      render: (_, __, index) => index + 1,
      width: 80,
    },
    {
      title: "邀请码",
      dataIndex: "inviteCode",
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (status) => {
        const color = status === "UNUSED" ? "blue" : "green";
        return <Tag color={color}>{status}</Tag>;
      },
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      render: (time) => dayjs(time).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "操作",
      render: (_, record) => {
        //  console.log(record)
        if (record.status === "UNUSED") {
          return (
            <Button
              icon={<CopyOutlined />}
              onClick={() => handleCopy(record.inviteCode)}
            >
              复制
            </Button>
          );
        } else {
          return (
            <Button
              disabled
              icon={<CopyOutlined />}
              // onClick={() => handleCopy(record.inviteCode)}
            >
              复制
            </Button>
          );
        }
      },
    },
  ];

  const createInvitation = async () => {
    const res = await service.post("admin/invites/generate");
    if (res) {
      copyTextFallback(code);
      // navigator.clipboard.writeText(res);
      message.success("验证码创建成功,已复制！");
    } else {
      message.error("验证码创建失败！");
    }
    fetchInvites();
  };
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        marginTop: "20px",
      }}
    >
      <div
        style={{
          width: "50vw",
          display: "flex",
          justifyContent: "right",
          marginBottom: 16,
        }}
      >
       {role==='ADMIN' && <Button
          //   icon={<UploadOutlined />}
          type="primary"
          onClick={() => createInvitation()}
        >
          生成验证码
        </Button>}
      </div>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        loading={loading}
        pagination={false}
      />
    </div>
  );
};

export default Invitation;
